;
(function (window, angular) {
    'use strict';
    angular.module("login.manager", ["pascalprecht.translate", "ui.router", "ngSanitize", "ui.bootstrap", "angular.filter", "YB.Widget", "Directive.All", "Service.All", "Filter.All", "template-widget"])
        .run(["ybConfig", "$state", function (ybConfig, $state) {
            ybConfig.initConfig();
            $state.go('login');
        }])

        .config(['$qProvider', '$locationProvider', function($qProvider, $locationProvider) {
            // 禁用默认的警告日志（可选）
            $qProvider.errorOnUnhandledRejections(false);

            // Hashbang 模式 改成 普通哈希模式
            $locationProvider.hashPrefix('');
        }])

        // 国际化
        .config(["$translateProvider", function ($translateProvider) {

            $translateProvider.preferredLanguage(localStorage.getItem('lang') || 'zh-CN');

            $translateProvider.useStaticFilesLoader({
                prefix: 'i18n/',
                suffix: '.json'
            });
        }])

        .config(['$stateProvider', "$logProvider", function ($stateProvider, $logProvider) {
            /*  不登录直接访问页面方法：
                在login.js文件里定义的.config(['$stateProvider'路由
                访问方式：host/#/antiFake?barcode=
            */

            $logProvider.debugEnabled(true);

            $stateProvider.state("login", {
                url: "/login",
                templateUrl: "view/login/login.html",
                controller: "LoginPageCtrl"
            });

            $stateProvider.state("register", {
                url: "/register",
                templateUrl: "view/login/register.html",
                controller: "RegisterCtrl"
            });

            $stateProvider.state("check", {
                url: "/check",
                templateUrl: "view/login/check.html",
                controller: "CheckPageCtrl"
            });

            $stateProvider.state("antiFake", {
                url: "/antiFake",
                templateUrl: "view/login/antiFake.html",
                controller: "AntiFakeCtrl"
            });

            $stateProvider.state("barcodeBox", {
                url: "/barcodeBox",
                templateUrl: "view/login/barcodeBox.html",
                controller: "BarcodeBoxCtrl"
            });

            $stateProvider.state("download", {
                url: "/download",
                templateUrl: "view/login/download.html",
                controller: "DownloadCtrl"
            });

            $stateProvider.state("potentialSupply", {
                url: "/potentialSupply",
                templateUrl: "view/login/potentialSupply.html",
                controller: "PotentialSupplyCtrl"
            });

            $stateProvider.state("changePasswd", {
                is18n: true,
                url: "/changePasswd",
                templateUrl: "view/login/changePasswd.html",
                controller: "ChangePasswdCtrl"
            });
        }])
        .controller("RegisterCtrl", ['$scope','$state','ybHttp','ybWidget','MESG_TYPE',function ($scope,$state,ybHttp,ybWidget,MESG_TYPE) {
            $scope.failRegister = false;
            $scope.showFormError = false;
            $scope.orgObj = {};
            $scope.xcmg_version = '';
            $scope.resetMessage = function () {
                $scope.failRegister = false;
            };
            $scope.cancel = function () {
                $state.go('login');
            };
            $scope.doRegister = function (isValid) {
                if (!isValid) {
                    $scope.showFormError = true;
                    return;
                }
                $scope.showFormError = false;
                var service = "device";
                var reqUrl = "/company/register";
                ybHttp.Post(service, reqUrl,$scope.orgObj).then(function (resp) {
                    if(resp.code != 0){
                        $scope.failRegister = true;
                        $scope.Message = resp.message;
                        return;
                    }
                    $scope.failRegister = false;
                    ybWidget.ShowMessage('注册成功，请等待平台通知',MESG_TYPE.Success).then(function (data) {
                        $state.go('login');
                    });
                })
            };
            function getVersion() {
                var service = "device";
                var reqUrl = "/dataDictionary/version";
                ybHttp.Get(service, reqUrl).then(function (resp) {
                    $scope.xcmg_version = resp;
                });
            }
            (function () {
                getVersion();
            })();
        }])
        .controller("LoginPageCtrl", ['$scope', '$window', "UserContextService", 'ybHttp', 'ybWidget', 'ybConfig','$state', 'MESG_TYPE', '$filter', function ($scope, $window, UserContextService, ybHttp, ybWidget, ybConfig,$state,MESG_TYPE,$filter) {
            $scope.failLogin = false;
            $scope.showFormError = false;
            $scope.user = {"loginName": "", "password": "", code: ""};
            $scope.resetMessage = function () {
                $scope.failLogin = false;
            };
            $scope.codeImg = '';
            $scope.xcmg_version = '';
            var authId = '';
            function getUpdateTime(){
                var service = "device";
                var reqUrl = "/sysIteration/tip";
                ybHttp.Get(service, reqUrl,{}).then(function (data) {
                    var resT = data.value || {};
                    $scope.updateTime = resT.iterateTime;
                    if($scope.updateTime == undefined || $scope.updateTime == ''){
                        $scope.tipFlase = false;
                        return;
                    }
                    $scope.tipFlase = true;
                    $scope.iterateContents = resT.iterateContents;
                })
            }
            function getAuthCode() {
                var service = "auth";
                var reqUrl = "/auth/authInfo";
                ybHttp.Get(service, reqUrl).then(function (data) {
                    if(data.code != 0){
                        ybWidget.ShowMessage(data.message);
                        return;
                    }
                    authId = data.value.authId;
                    $scope.codeImg = ybConfig.getConfig().serviceName.auth + '/auth/kaptcha?authid=' + data.value.authId;
                })
            }

            function getVersion() {
                var service = "device";
                var reqUrl = "/dataDictionary/version";
                ybHttp.Get(service, reqUrl).then(function (resp) {
                    $scope.xcmg_version = resp;
                });
            }

            function getLoginIpInfo() {
                ybHttp.Get("device", "/logininfo/abnormalLogin").then(function (data) {
                    if (data.value) {
                        var loginDate = $filter("YbDate")(data.value.loginDate, 'yyyy-MM-dd HH:mm:ss');
                        var loginIp = data.value.loginIp || '';
                        var loginIpHome = data.value.ipHome || '';

                        var msg = "系统检测到您本次登录的ip信息与上次不同。<div class='abnormal-msg'><span>上次登录信息：</span>登录时间：" + loginDate + '<br/>登录ip：' + loginIp + '<br/>ip归属地：' + loginIpHome + '</div>'
                        var okName = '确定'
                        if (localStorage.getItem('lang') == 'en-US') {
                            msg = "The system detects that the ip information you log in this time is different from the last time。<div class='abnormal-msg'><span>Last login info：</span>Login time：" + loginDate + '<br/>Login ip：' + loginIp + '<br/>Ip attribution：' + loginIpHome + '</div>'
                            okName = 'Confirm'
                        } else if (localStorage.getItem('lang') == 'es-ES') {
                            msg = "El sistema ha detectado que su información ip para este inicio de sesión es diferente de la última vez。<div class='abnormal-msg'><span>Última información de acceso：</span>Hora de inicio：" + loginDate + '<br/>Iniciar sesión ip：' + loginIp + '<br/>Lugar de propiedad ip：' + loginIpHome + '</div>'
                            okName = 'Determinar'
                        } else if (localStorage.getItem('lang') == 'in') {
                            msg = "Sistem mendeteksi ip informasi-mu untuk masuk berbeda dari terakhir kali。<div class='abnormal-msg'><span>Informasi login terakhir：</span>Log masuk waktu：" + loginDate + '<br/>Masuk ip：' + loginIp + '<br/>Ip milik：' + loginIpHome + '</div>'
                            okName = 'yakin'
                        } else if (localStorage.getItem('lang') == 'ru') {
                            msg = "Система обнаружила, что ip-сообщение, которое вы залогинились на этот раз, отличается от предыдущего。<div class='abnormal-msg'><span>Последний логин：</span>Время входа：" + loginDate + '<br/>Логин：' + loginIp + '<br/>Ip-адрес：' + loginIpHome + '</div>'
                            okName = 'увер'
                        }
                        
                        ybWidget.ShowMessage(msg, MESG_TYPE.Warn, {isHtml: true, okName}).then(function (data) {
                            $window.location.href = "main.html";
                        });
                    } else {
                        $window.location.href = "main.html";
                    }
                }, function() {
                    $window.location.href = "main.html";
                });
            }

            $scope.login = function (isValid) {
                if (!isValid) {
                    $scope.showFormError = true;
                    return;
                }
                $scope.showFormError = false;
                $scope.user.authId = authId;
                var result = UserContextService.Login($scope.user);
                result.then(function () {
                    if (UserContextService.GetPwdLevel($scope.user.password)<=1) {
                        UserContextService.Logout(false, true);
                        ybWidget.ShowMessage("密码过于简单，请修改后再登录", MESG_TYPE.Warn).then(function () {
                            $window.location.href = "#/changePasswd?loginname="+$scope.user.loginName;
                        });
                    } else {
                        $scope.failLogin = false;
                        getLoginIpInfo();
                    }
                },function (data) {
                    $scope.failLogin = true;
                    $scope.Message = data;
                    $scope.refresh();
                });
            };
            $scope.goRegister = function () {
                $state.go('register');
            };
            $scope.refresh = function () {
                getAuthCode();
            };

            (function () {
                getAuthCode();
                getVersion();
                getUpdateTime();
            })();
        }])

        .controller("AntiFakeCtrl", ['$scope', 'ybHttp', 'ybWidget', '$location', 'EventBus', function ($scope, ybHttp, ybWidget, $location, EventBus) {

            function initPageData() {
                var service = "device";
                var reqUrl = "/barcode/checkBarcode";
                var params = {
                    barcode: $location.search().barcode || ''
                };
                ybHttp.Post(service, reqUrl, params).then(function (data) {
                    if (data.code != 0) {
                        ybWidget.ShowMessage(data.message);
                        return;
                    }
                    $scope.antiFakeObj = data.value || {};
                })
            }
            (function () {
                if(!!$location.search().barcode){
                    const englishStrs = ['en', 'en-US'] // 安卓是en，ios是en-US
                    
                    let getPrintType = $location.search().printType || ''
                    if (getPrintType && getPrintType == 5) {
                        // 获取打印模板配置 如果为进出口的,防伪页面为英文
                        $scope.isEnglishUser = true
                    }else {
                        $scope.isEnglishUser = englishStrs.includes(navigator.language)
                    }
                    initPageData();
                }
            })();
        }])

        .controller("BarcodeBoxCtrl", ['$scope', 'ybHttp', 'ybWidget', '$location', function ($scope, ybHttp, ybWidget, $location) {

            function initPageData() {
                var service = "device";
                var reqUrl = "/deliveryReceipt/getSinglePrintBoxupInfo";
                var params = {
                    boxupId: $location.search().boxupId || ''
                };
                ybHttp.Get(service, reqUrl, params).then(function (data) {
                    if (data.code != 0) {
                        ybWidget.ShowMessage(data.message);
                        return;
                    }
                    $scope.barcodeBoxInfo = data.value || {};
                })
            }
            $scope.newTbConf = {
                scrollWidth: 200,
                tableCol: [
                    {
                        name: "零件号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "数量",
                        width: 150,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                ]
            };


            (function () {
                if(!!$location.search().boxupId){
                    initPageData();
                }
            })();
        }])

        .controller("CheckPageCtrl", ['$scope', 'ybHttp', 'ybWidget', '$location', function ($scope, ybHttp, ybWidget, $location) {

            function initPageData() {
                var service = "device";
                var reqUrl = "/shell/check";
                var params = {
                    digitCode: $location.search().digitCode || ''
                };
                ybHttp.Get(service, reqUrl, params).then(function (data) {
                    if (data.code != 0) {
                        ybWidget.ShowMessage(data.message);
                        return;
                    }
                    $scope.checkData = data.value || {};
                })
            }

            (function () {
                if(!!$location.search().digitCode){
                    initPageData();
                }
            })();
        }])

        .controller("IndexCtrl", ['$translate', '$rootScope', '$scope', 'EventBus', function ($translate, $rootScope, $scope, EventBus) {
            $scope.sysName = window.AppData.config.otherData.sysName;

            $scope.currentLan = $translate.preferredLanguage();
            $rootScope.isEN = judgeEnvIsEn($scope.currentLan);
            $rootScope.isES = judgeEnvIsEs($scope.currentLan);
            $scope.switchLan = function (val) {
                $rootScope.isEN = judgeEnvIsEn(val);
                $rootScope.isES = judgeEnvIsEs(val);
                localStorage.setItem('lang', val);
                $translate.use(val);
            };

            function judgeEnvIsEn(lan) {
                return lan == 'en-US'
            }
            function judgeEnvIsEs(lan) {
                return lan == 'es-ES'
            }

            EventBus.Subscribe("changeLan4Page", changeLan4Page);

            function changeLan4Page(val) {
                $scope.currentLan = val;
                $scope.switchLan(val);
            }
        }])

        .controller("DownloadCtrl", ["$scope", "ybHttp", "ybConfig", "UserContextService", function ($scope, ybHttp, ybConfig, UserContextService) {
            
            function isWeiXin () {
                var ua = window.navigator.userAgent.toLowerCase()
                return ua.match(/MicroMessenger/i) == 'micromessenger'
            }

            (function () {
                const paramsMap = UserContextService.ParseUrlParams()
                const supportTypes = ['1']
                if (!supportTypes.includes(paramsMap.type)) {
                    alert('下载链接不正确！')
                    return
                }

                let apkNameTemp = ''
                let apkImgUrlTemp = ''
                switch (paramsMap.type) {
                    case '1':
                        apkNameTemp = '广汽仓储PDA'
                        apkImgUrlTemp = '../../assets/img/PDA_logo.png'
                        break;
                    default:
                        break;
                }

                $scope.apkName = apkNameTemp
                $scope.apkImgUrl = apkImgUrlTemp

                $scope.isWX = isWeiXin()
                if (!$scope.isWX) {
                    ybHttp.Get('device', '/appSetting/itemLatestByType', { type: paramsMap.type }).then(function (resp) {
                        if (!resp.value) {
                            return;
                        }
                        $scope.apkVersion = resp.value.version;
                        $scope.apkUrl = ybConfig.getConfig().baseUrl.ImgMinioUrl + resp.value.updateUrl;
                    });
                }
            })();
        }])

        .controller("PotentialSupplyCtrl", ['$scope', 'ybHttp', 'ybWidget', '$location', 'MESG_TYPE', function ($scope, ybHttp, ybWidget, $location, MESG_TYPE) {
            $scope.submitted = false;
            $scope.detailInfo = {};

            $scope.onContactTelChange = function(val, isError) {
                if ($scope.signFlag && !isError) {
                    const params = {
                        contactTel: val,
                        sign: $scope.signFlag
                    }
                    ybHttp.Get("device", '/wjSupplierApply/visitorDetail', params).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error, { size: 'sm' });
                            return;
                        }
            
                        $scope.detailInfo = resp.value || {};
                    });
                }
            };

            $scope.saveData = function (isValid) {
                if (!isValid) {
                  $scope.submitted = true;
                  return;
                }

                ybHttp.Post("device", "/wjSupplierApply/visitorSave", $scope.detailInfo).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error, { size: 'sm' });
                        return;
                    }

                    ybWidget.ShowMessage('操作成功', MESG_TYPE.Success, { size: 'sm' });
                    $scope.detailInfo = {};
                    $scope.submitted = false;
                });
            };

            (function () {
                $scope.signFlag = $location.search().sign;
            })();
        }])

        .controller("ChangePasswdCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, $stateParams) {
            $scope.submitted = false;
            $scope.detailInfo = {
                oldPwd: "",
                newPwd: "",
                confirmPwd: ""
            };

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }

                if ($scope.detailInfo.newPwd !== $scope.detailInfo.confirmPwd) {
                    return;
                }
                var service = "auth";
                var param = {
                    oldPassword: $scope.detailInfo.oldPwd,
                    newPassword: $scope.detailInfo.newPwd,
                    confirmPassWord: $scope.detailInfo.confirmPwd,
                    loginName: $scope.loginname,
                };
                ybHttp.Post(service, $scope.reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.submitted = false;
                    ybWidget.ShowMessage("操作成功<br>请重新登录", MESG_TYPE.Success, {isHtml: true}).then(function () {
                        UserContextService.Logout();
                    });
                });
            };

            $scope.progressBar = {
                value: '25',
                title: '很低',
                class: 'progress-bar-danger'
            };
            $scope.handleLevelChange = function (val) {
                switch (val) {
                    case 0:
                    case 1:
                        $scope.progressBar = {
                            value: '25',
                            title: '很低',
                            class: 'progress-bar-danger'
                        };
                        break
                    case 2:
                        $scope.progressBar = {
                            value: '45',
                            title: '低',
                            class: 'progress-bar-warning'
                        };
                        break
                    case 3:
                        $scope.progressBar = {
                            value: '65',
                            title: '中',
                            class: 'progress-bar-info'
                        };
                        break
                    case 4:
                        $scope.progressBar = {
                            value: '100',
                            title: '强',
                            class: 'progress-bar-success'
                        };
                        break
                  }
            }

            function getUrlParams(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
                var parm = window.location.hash.split("?")[1];
                if (parm == null) return null;
                var r = parm.match(reg);
                if (r == null) return null;
                return unescape(r[2]);
            }

            (function () {
                var loginnameVal = getUrlParams("loginname");
                $scope.reqUrl = "/auth/password";
                if ($scope.curUser && $scope.curUser.loginName) {
                    $scope.loginname = $scope.curUser.loginName;
                } else if(loginnameVal) {
                    $scope.loginname = loginnameVal;
                    $scope.reqUrl = "/auth/passwordModify";
                }
            })();
        }])
    ;
})(window, window.angular);